<?php
/**
 * Created by PhpStorm
 * User: huangjiacheng
 * Date: 2023/6/5
 * Time: 16:25
 */

namespace app\command;

use think\facade\Db;
use think\console\input\Option;
use think\console\Command;
use think\facade\Console;
use think\console\Output;
use think\console\Input;


class AutoSell extends Command
{
    protected $myConfig = [
        'licence' => '240173e804a5948d95',
        'ssjy' => 'https://api.mairuiapi.com/hsstock/real/time', //  实时交易
        'macd' => 'https://api.mairuiapi.com/hszb/macd/',
        'rsi'	=> '',
        'config' => [
            1 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=19d0274f-23d2-4e8b-a301-a72035577f50',
                'trade_table' =>  'trade_code',
                'date_table' =>  'zj_info_date',
                'min_yuer'  =>  10000,  //不满仓，保留余额
                'max_buy_price' => 100, // 最多价格
                'per_buy'   =>  10000,  //每次购买最大价格
            ],
            2 => [
                'qywx' => 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=538e972d-b83b-4c8e-8eb0-7e857dc95637',
                'trade_table' =>  'trade_two_code',
                'date_table' =>  'zj_two_info_date',
                'min_yuer'  =>  5000,
                'max_buy_price' => 50,
                'per_buy'   =>  5000,  //每次购买最大价格
            ],

        ],
    ];
    protected function configure()
    {
        $this->setName('auto:sell')
            ->addOption('config', null, Option::VALUE_REQUIRED, '第几梯队')
            ->setDescription('auto_sell信息脚本');
    }
    protected function execute(Input $input, Output $output){
        $output->info('这是auto_sell信息脚本');
        $config = $input->getOption('config');
        $today  = date("Y-m-d");
        $sql = "select * from holiday where holiday>='$today' ";
        $list = Db::query($sql);
        $holiday_list = array_column($list,'holiday');
        if (in_array($today,$holiday_list)){
            $output->info('today is holiday');
            return ;
        }

        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where sell=0 and buy_date<'$today'";
        $list = Db::query($sql);
        $msg = '';
        $list_count = count($list);

        foreach ($list as $row) {
            try {
                $code = $row['code'];
                $url= $this->myConfig['ssjy']."/".$code."/".$this->myConfig['licence'];
                $str=file_get_contents($url);
                sleep(2);
                $data=json_decode($str,true);
                if (empty($data['p'])) {
                    $i= 0;
                           sleep(2);
                    while (1) {
                        $url= $this->myConfig['ssjy']."/".$code."/".$this->myConfig['licence'];
                        $str=file_get_contents($url);
                        sleep(2);
                        $data=json_decode($str,true);
                        if (!empty($data['p'])) {
                            break;
                        }
                        if ($i >20) {
                            break;
                        }
                        $i++;
                    }
                }

                if (!empty($data['p'])){
                    $diff_day = (strtotime($today) - strtotime($row['buy_date']))/86400;
                    if ($diff_day >=15) {

                        if ( $data['p'] >= $row['buy'] ){
                            $this->sell_code($row['id'],$data['p'],$config);
                            $msg =$row['code']."|".$data['p']."|".round(($data['p']-$row['buy'])*$row['buy_num'],2)."| ".round((100*($data['p']-$row['buy'])/$row['buy']),2)."(%)\n";
                            $this->alarm($msg,$config);
                            $list_count = $list_count-1 ;
                        }else if ($data['p'] >= $row['buy']*0.98 && $list_count >=12 && date("H") >= 10){
                            // 持仓大于14天 一般为10个交易日,亏损小于2.5个点
                            $this->sell_code($row['id'],$data['p'],$config);
                            $msg =$row['code']."|".$data['p']."|".round(($data['p']-$row['buy'])*$row['buy_num'],2)."| ".round((100*($data['p']-$row['buy'])/$row['buy']),2)."(%)\n";
                            $this->alarm($msg,$config);
                            $list_count = $list_count-1 ;
                        }else if ($list_count >= 12  && date("H") == 14) {
                            $this->sell_code($row['id'],$data['p'],$config);
                            $msg =$row['code']."|".$data['p']."|".round(($data['p']-$row['buy'])*$row['buy_num'],2)."| ".round((100*($data['p']-$row['buy'])/$row['buy']),2)."(%)\n";
                            $this->alarm($msg,$config);
                            $list_count = $list_count-1 ;
                        }
                    }
                    //亏20点补
                    if ($data['p'] <= $row['buy']*0.8){

                        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where sell=0 and buy_date<='$today' and `code`='".$row['code']."'";
                        $listNumList = Db::query($sql);
                        if (count($listNumList) < 2) {
                            $this->buyCode($row['code'],$data['p'],$config);
                        }
                    }
                    $this->count_price($row['id'],$data['p'],$config);
                }
            }catch (\Exception $e) {
                echo $e;
            }
        }
    }

    protected function alarm($msg,$config){
        $webhook = $this->myConfig['config'][$config]['qywx'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $webhook);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
        $post_data = [
            'msgtype' => 'text',
            'text' => [
                'content' => "【".date("Y-m-d H:i:s")."】【Auto_Sell】"."\n".$msg,
            ]
        ];
        $post_data = json_encode($post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($curl);
        var_dump($data);
        curl_close($curl);
    }
    protected function count_price($id,$price,$config){
        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where id ='$id' ";
        $list = Db::query($sql);
        $row = $list[0];
        $yingkui = ($price-$row['buy'])/$row['buy'];
        $update = "update ".$this->myConfig['config'][$config]['trade_table']." set cur_price='$price',yingkui='$yingkui' where id='$id'";
        Db::query($update);
    }
    protected function sell_code($id,$price,$config){
        $sql = "select * from ".$this->myConfig['config'][$config]['trade_table']." where id ='$id' ";
        $list = Db::query($sql);
        $row = $list[0];

        $sell_date = date("Y-m-d");
        $update = "update ".$this->myConfig['config'][$config]['trade_table']." set sell='$price',sell_date='$sell_date' where id='$id'";
        Db::query($update);


        $change_num = $price * $row['buy_num'];
        $chicang_change = $row['buy'] * $row['buy_num'];

        $sql = "select * from zj_info where id ='".$config."'";
        $list = Db::query($sql);
        $row = $list[0];


        $yuer = $row['yuer'] + $change_num;
        $chicang = $row['chicang'] - $chicang_change ;

        $shizhi = $yuer+$chicang ;
        $yingkui = ($shizhi/$row['bj'] - 1)*100;
        $update = "update zj_info set yuer = '$yuer',chicang='$chicang',shizhi='$shizhi',yingkui='$yingkui'  where id ='".$config."'";
        Db::query($update);
    }
    protected function buyCode($code,$price,$config){
        $sql = "select * from zj_info where id ='".$config."' ";
        $list = Db::query($sql);
        $row = $list[0];
        if ($row['yuer'] <$this->myConfig['config'][$config]['min_yuer']) {
            return false;
        }else{
            if ($price >=$this->myConfig['config'][$config]['max_buy_price']) {
                return false;
            }
            $num = intval($this->myConfig['config'][$config]['per_buy']/($price*100)); //
            $buy_num = 100 *$num;
            $buy_date = date("Y-m-d");
            $insert="insert into ".$this->myConfig['config'][$config]['trade_table']."(`code`,`buy`,`buy_num`,`buy_date`,`sell`) 
				values('$code','$price','$buy_num','$buy_date','0')";
            Db::query($insert);
            $this->alarm("buy:".$code.",".$price.",".$buy_num,$config);
            $yuer = $row['yuer'] - ($price*$buy_num);
            $chicang = $row['chicang'] + ($price*$buy_num);
            $update = "update zj_info set yuer = '$yuer',chicang='$chicang'  where id ='".$config."' ";
            Db::query($update);

            $msg = $code.'|'.$price."|".$buy_num;

            $webhook = $this->myConfig['config'][$config]['qywx'];
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $webhook);
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json;charset=utf-8'));
            $post_data = [
                'msgtype' => 'text',
                'text' => [
                    'content' => "【buy:".date("Y-m-d H:i:s")."】\n".$msg,
                ]
            ];
            $post_data = json_encode($post_data);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            $data = curl_exec($curl);
            curl_close($curl);
        }

    }
}